#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <semaphore.h>

#include <stdlib.h>
#include <unistd.h>
#include <time.h>

#include <sys/stat.h>
#include <string.h>

#define  SEM_NAME "mysem"
#define  SEM_NAME2 "mysem2"
#define  DATA_FILE "a.txt"

int main(int argc, char const *argv[])
{
    // 1. 创建或打开信号量
    sem_t *sem1 = sem_open(SEM_NAME, O_CREAT|O_RDWR,0644, 1);
    if(sem1 == SEM_FAILED){
        perror("sem_open");
        return -1;
    }
    printf("%s open成功\n", SEM_NAME);

    // 用于通知第二个程序可以处理数据
    sem_t *sem2 = sem_open(SEM_NAME2, O_CREAT|O_RDWR,0644, 0);

    srand(time(NULL));
    // 2. 打开数据文件
    char buf[10] = "";
    for(int i=0;i<5; i++){
        sem_wait(sem1);
        int fd = open(DATA_FILE, O_CREAT|O_WRONLY|O_APPEND, 0644);
        // 随机生成5个整数，并写入到a.txt文件中
        int num = rand() % 900 + 100; // [100, 999]
        sprintf(buf, "%d\n", num);
        write(fd, buf, 4);
        printf("-- 生成新数据%d 成功---\n", num);

        bzero(buf, 10);
        close(fd);
        sem_post(sem2);

    }
    sem_close(sem1);  // 关闭信号量
    sem_close(sem2);  // 关闭信号量
    return 0;
}
